#!/usr/bin/env python
# coding:utf-8

import cyclone.auth
import cyclone.escape
import cyclone.web
from toughadmin.tools import utils
from toughadmin.console.admin.base import BaseHandler, MenuRes
from toughadmin.tools.permit import permit
from toughadmin.console import models
from toughadmin.console.admin import policy_server_forms
from twisted.internet import defer
from twisted.python import log
from cyclone import httpclient
import json


@defer.inlineCallbacks
def setPolicyServerUpdate(db):
    radius_list = db.query(models.TraRadius)
    for radius in radius_list:
        count = 0
        while(count < 3):
            try:
                response = yield httpclient.fetch("http://%s:%s/api/policyServerUpdate" %(radius.ip_addr,int(radius.admin_port)),postdata="policyServerUpdate",headers={"Content-Type": ["application/json"]})
                resp_msg = json.loads(response.body)
                if resp_msg['code'] == 1:
                    count += 1
                else: break
            except Exception, e:
                import traceback
                log.msg("update policy server can not connect %s error" %radius.ip_addr)
                traceback.print_exc()
                break


class PolicyServerHandler(BaseHandler):
    @cyclone.web.authenticated
    def get(self):
        self.render("policy_server_list.html",policy_status=policy_server_forms.boolean,
                      policy_server_list=self.db.query(models.TraPolicyServer))

class AddHandler(BaseHandler):
    @cyclone.web.authenticated
    def get(self):
        self.render("base_form.html", form=policy_server_forms.policy_add_form())

    @cyclone.web.authenticated
    def post(self):
        form = policy_server_forms.policy_add_form()
        if not form.validates(source=self.get_params()):
            self.render("base_form.html", form=form)
            return
        if self.db.query(models.TraPolicyServer).filter_by(policy_server_ip=form.d.policy_server_ip).count() > 0:
            self.render("base_form.html", form=form, msg=u"策略服务器已经存在")
            return
        policy_server = models.TraPolicyServer()
        policy_server.policy_server_ip = form.d.policy_server_ip
        policy_server.policy_auth_port = form.d.policy_auth_port
        policy_server.policy_acct_port = form.d.policy_acct_port
        policy_server.status = form.d.status
        policy_server.secret = form.d.secret
        self.db.add(policy_server)

        if form.d.status == '1':
            self.db.query(models.TraPolicyServer).filter(models.TraPolicyServer.policy_server_ip != form.d.policy_server_ip).update({'status':0})

        ops_log = models.TraOperateLog()
        ops_log.operator_name = self.get_secure_cookie("tra_user")
        ops_log.operate_ip = self.get_secure_cookie("tra_login_ip")
        ops_log.operate_time = utils.get_currtime()
        ops_log.operate_desc = u'操作员(%s)新增策略服务器信息:%s' % (ops_log.operator_name, policy_server.policy_server_ip)
        self.db.add(ops_log)
        self.db.commit()

        yield setPolicyServerUpdate(self.db)

        self.redirect("/policy",permanent=False)


class UpdateHandler(BaseHandler):
    @cyclone.web.authenticated
    def get(self):
        policy_id = self.get_argument("policy_id")
        policy_server = self.db.query(models.TraPolicyServer).get(policy_id)
        form = policy_server_forms.policy_update_form()
        form.fill(policy_server)
        return self.render("base_form.html", form=form)

    def post(self):
        form = policy_server_forms.policy_update_form()
        if not form.validates(source=self.get_params()):
            self.render("base_form.html", form=form)
            return
        policy_server = self.db.query(models.TraPolicyServer).get(form.d.id)
        policy_server.policy_server_ip = form.d.policy_server_ip
        policy_server.policy_auth_port = form.d.policy_auth_port
        policy_server.policy_acct_port = form.d.policy_acct_port
        policy_server.secret = form.d.secret

        ops_log = models.TraOperateLog()
        ops_log.operator_name = self.get_secure_cookie("tra_user")
        ops_log.operate_ip = self.get_secure_cookie("tra_login_ip")
        ops_log.operate_time = utils.get_currtime()
        ops_log.operate_desc = u'操作员(%s)修改策略服务器信息:%s' % (ops_log.operator_name, policy_server.policy_server_ip)
        self.db.add(ops_log)
        self.db.commit()

        yield setPolicyServerUpdate(self.db)
        self.redirect("/policy",permanent=False)


class DeleteHandler(BaseHandler):
    @cyclone.web.authenticated
    def post(self):
        policy_id = self.get_argument("policy_id")

        policy_server = self.db.query(models.TraPolicyServer).filter(models.TraPolicyServer.id==policy_id,
                                                                     models.TraPolicyServer.status==1).first()

        if policy_server:
            self.render_json(code=1, msg=u"此策略服务器正处于活动状态,不允许删除")
            return

        self.db.query(models.TraPolicyServer).filter_by(id=policy_id).delete()

        ops_log = models.TraOperateLog()
        ops_log.operator_name = self.get_secure_cookie("tra_user")
        ops_log.operate_ip = self.get_secure_cookie("tra_login_ip")
        ops_log.operate_time = utils.get_currtime()
        ops_log.operate_desc = u'操作员(%s)删除策略服务器信息:%s' % (ops_log.operator_name, policy_id)
        self.db.add(ops_log)
        self.db.commit()

        yield setPolicyServerUpdate(self.db)
        self.render_json(code=0,msg=u'success')


class ActivateHandler(BaseHandler):
    @cyclone.web.authenticated
    def get(self):
        policy_id = self.get_argument("policy_id")
        self.db.query(models.TraPolicyServer).filter(id!=policy_id).update({'status':0})
        policy_server = self.db.query(models.TraPolicyServer).filter_by(id=policy_id).first()
        policy_server.status = 1

        ops_log = models.TraOperateLog()
        ops_log.operator_name = self.get_secure_cookie("tra_user")
        ops_log.operate_ip = self.get_secure_cookie("tra_login_ip")
        ops_log.operate_time = utils.get_currtime()
        ops_log.operate_desc = u'操作员(%s)激活策略服务器信息:%s' % (ops_log.operator_name, policy_id)
        self.db.add(ops_log)
        self.db.commit()

        yield setPolicyServerUpdate(self.db)
        self.redirect("/policy",permanent=False)


permit.add_route(PolicyServerHandler, r"/policy", u"策略服务器管理", MenuRes, order=2.0200, is_menu=True)
permit.add_route(AddHandler, r"/policy/add", u"策略服务器新增", MenuRes, order=2.0201, is_menu=False)
permit.add_route(UpdateHandler, r"/policy/update", u"策略服务器修改", MenuRes, order=2.0202, is_menu=False)
permit.add_route(DeleteHandler, r"/policy/delete", u"策略服务器删除", MenuRes, order=2.0203, is_menu=False)
permit.add_route(ActivateHandler, r"/policy/activate", u"策略服务器激活", MenuRes, order=2.0204, is_menu=False)